<script setup lang="tsx">
import { h, onMounted, ref } from 'vue';
import type { Ref } from 'vue';
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { useBoolean } from '@sa/hooks';
import type { Menu } from '@/service/api';
import { deleteMenus, fetchGetAllPages, fetchGetMenuList } from '@/service/api';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import { MenuTypeEnum, yesOrNoRecord } from '@/constants/common';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { useAuth } from '@/hooks/business/auth';
import { localStg } from '@/utils/storage';
import { DICT_TYPE, getDictObj } from '@/utils/dict';
import MenuOperateModal, { type OperateType } from './modules/menu-operate-modal.vue';
import MenuSearch from './modules/menu-search.vue';

const appStore = useAppStore();
const { hasAuth } = useAuth();

const { bool: visible, setTrue: openModal } = useBoolean();

const wrapperRef = ref<HTMLElement | null>(null);

const {
  columns,
  columnChecks,
  data,
  loading,
  mobilePagination,
  getData,
  getDataByPage,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetMenuList,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    // if you want to use the searchParams in Form, you need to define the following properties, and the value is null
    // the value can not be undefined, otherwise the property in Form will not be reactive
    status: null,
    menuName: null
  },
  columns: () => [
    {
      type: 'selection'
    },
    {
      key: 'menuName',
      title: $t('page.manage.menu.menuName'),
      width: 300,
      render: row => {
        const { i18nKey, menuName } = row;

        const label = i18nKey ? $t(i18nKey) : menuName;

        return <span>{label}</span>;
      }
    },
    {
      key: 'menuType',
      title: $t('page.manage.menu.menuType'),
      align: 'center',
      width: 80,
      render: row => {
        const dictObj = getDictObj(DICT_TYPE.SYSTEM_MENU_TYPE, row.menuType);

        return <NTag type={dictObj?.colorType}>{dictObj?.label}</NTag>;
      }
    },
    {
      key: 'permission',
      title: $t('page.manage.menu.permission'),
      align: 'center',
      minWidth: 150
    },
    {
      key: 'icon',
      title: $t('page.manage.menu.icon'),
      align: 'center',
      width: 80,
      render: row => {
        if (row.iconType) {
          const icon = row.iconType.toString() === '1' ? row.icon : undefined;

          const localIcon = row.iconType.toString() === '2' ? row.icon : undefined;

          return (
            <div class="flex-center">
              <SvgIcon icon={icon} localIcon={localIcon} class="text-icon" />
            </div>
          );
        }
        return <div class="flex-center">-</div>;
      }
    },
    {
      key: 'routeName',
      title: $t('page.manage.menu.routeName'),
      align: 'center',
      minWidth: 120
    },
    {
      key: 'routePath',
      title: $t('page.manage.menu.routePath'),
      align: 'center',
      minWidth: 120
    },
    {
      key: 'status',
      title: $t('page.manage.menu.menuStatus'),
      align: 'center',
      width: 90,
      render: row => {
        if (row.status === null) {
          return null;
        }

        const dictObj = getDictObj(DICT_TYPE.COMMON_STATUS, row.status);

        return <NTag type={dictObj?.colorType}>{dictObj?.label}</NTag>;
      }
    },
    {
      key: 'hideInMenu',
      title: $t('page.manage.menu.hideInMenu'),
      align: 'center',
      width: 90,
      render: row => {
        const hide: CommonType.YesOrNo = row.hideInMenu ? 'Y' : 'N';

        const tagMap: Record<CommonType.YesOrNo, NaiveUI.ThemeColor> = {
          Y: 'error',
          N: 'default'
        };

        const label = $t(yesOrNoRecord[hide]);

        return <NTag type={tagMap[hide]}>{label}</NTag>;
      }
    },
    {
      key: 'parentId',
      title: $t('page.manage.menu.parentId'),
      width: 90,
      align: 'center'
    },
    {
      key: 'sort',
      title: $t('page.manage.menu.order'),
      align: 'center',
      width: 90
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 280,
      render: row => (
        <div class="flex-center justify-end gap-8px">
          {row.menuType.toString() === MenuTypeEnum.CATALOG && (
            <NButton type="primary" ghost size="small" onClick={() => handleAddChildMenu(row)}>
              {$t('page.manage.menu.addChildMenu')}
            </NButton>
          )}
          {row.menuType.toString() === MenuTypeEnum.MENU && (
            <NButton type="primary" ghost size="small" onClick={() => handleAddChildButton(row)}>
              {$t('page.manage.menu.addChildButton')}
            </NButton>
          )}
          <NButton type="primary" ghost size="small" onClick={() => handleEdit(row)}>
            {{
              default: () => $t('common.edit'),
              icon: () => h(SvgIcon, { icon: 'ep:edit' })
            }}
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton type="error" ghost size="small">
                  {{
                    default: () => $t('common.delete'),
                    icon: () => h(SvgIcon, { icon: 'ep:delete' })
                  }}
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ]
});

const { onDeleted } = useTableOperate(data, getData);

const operateType = ref<OperateType>('add');

function handleAdd() {
  operateType.value = 'add';
  openModal();
}

async function handleDelete(id: number) {
  // request
  await deleteMenus(id.toString());

  onDeleted(null);
}

/** the edit menu data or the parent menu data when adding a child menu */
const editingData: Ref<Menu | null> = ref(null);

function handleEdit(item: Menu) {
  operateType.value = 'edit';
  editingData.value = { ...item };

  openModal();
}

function handleAddChildMenu(item: Menu) {
  operateType.value = 'addChild';

  editingData.value = { ...item };

  openModal();
}

function handleAddChildButton(item: Menu) {
  operateType.value = 'addButton';

  editingData.value = { ...item };

  openModal();
}

const allPages = ref<string[]>([]);

async function getAllPages() {
  const { data: pages } = await fetchGetAllPages();
  allPages.value = pages || [];
}

/** 刷新菜单缓存按钮操作 */
const refreshMenu = async () => {
  try {
    window.$dialog?.info({
      title: $t('common.refreshMenu'),
      content: $t('common.refreshMenuTooltip'),
      positiveText: $t('common.confirm'),
      negativeText: $t('common.cancel'),
      onPositiveClick: () => {
        // 清空缓存信息
        localStg.remove('userInfo');
        // 刷新浏览器
        location.reload();
      }
    });
  } catch {}
};

function init() {
  getAllPages();
}

// init
onMounted(() => {
  init();
});
</script>

<template>
  <div ref="wrapperRef" class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <MenuSearch
      v-if="hasAuth('system:menu:query')"
      v-model:model="searchParams"
      @reset="resetSearchParams"
      @search="getDataByPage"
      @refresh="refreshMenu"
    />
    <NCard :title="$t('page.manage.menu.title')" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :loading="loading"
          create-auth="system:menu:create"
          delete-auth="system:menu:delete"
          delete-show="false"
          @add="handleAdd"
          @refresh="getData"
        />
      </template>
      <NDataTable
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="1088"
        :loading="loading"
        :row-key="row => row.id"
        remote
        :pagination="mobilePagination"
        class="sm:h-full"
      />

      <MenuOperateModal
        v-model:visible="visible"
        :operate-type="operateType"
        :row-data="editingData"
        :all-pages="allPages"
        @submitted="getDataByPage"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
